package org.geektimes.configuration.microprofile.config.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

/**
 @author :   chuan
 @date :   2021/03/20
 */
public abstract class MapBasedConfigSource implements ConfigSource {

    protected final Logger logger = Logger.getLogger(this.getClass().getName());

    private final String name;

    private final int ordinal;

    protected final ServletContext servletContext;

    private final Map<String, String> source;

    public MapBasedConfigSource(String name, int ordinal) {
        this(name, ordinal, null);
    }

    public MapBasedConfigSource(String name, int ordinal, ServletContext servletContext) {
        this.name = name;
        this.ordinal = ordinal;
        this.servletContext = servletContext;
        this.source = getProperties();
    }

    @Override
    public Map<String, String> getProperties() {
        Map<String, String> configData = new HashMap<>();
        try {
            prepareConfigData(configData);
        }catch (Throwable e){
            throw new IllegalStateException("准备配置数据发生错误", e);
        }
        return configData;
    }

    /**
      准备配置数据
     @param configData
     @throws Throwable
     */
    protected abstract void prepareConfigData(Map configData)throws Throwable;

    @Override
    public int getOrdinal() {
        return this.ordinal;
    }

    @Override
    public Set<String> getPropertyNames() {
        return source.keySet();
    }

    @Override
    public String getValue(String propertyName) {
        return source.get(propertyName);
    }

    @Override
    public String getName() {
        return this.name;
    }
}
